<template>
  <div class="card-box">
    <!-- <basic-info /> -->
    <!-- <check-content />
    <approval-info /> -->
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      label-width="100px"
      class="form__content"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="审批结果" prop="approveResult">
            <el-radio-group v-model="formData.approveResult">
              <el-radio label="1">验收通过</el-radio>
              <el-radio label="0">验收不通过</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="审批意见" prop="opinion">
            <ReFastInput @emitFastInput="emitFastInput" />

            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="formData.opinion"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="content-footer">
      <el-button type="primary" @click="handleSave">保 存</el-button>
      <el-button type="primary" @click="handleSubmit">提 交</el-button>
      <el-button type="primary" @click="handleReject">驳 回</el-button>
    </div>
    <el-dialog
      title="专业组长审批"
      v-model="commitVisible"
      destroy-on-close
      width="600px"
    >
      <div class="dialog__content">
        <!-- <div class="dialog__content--title">任务基本信息:</div> -->
        <div style="width: 100%; text-align: center; padding: 20px 0">
          是否确定提交？
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="commitVisible = false">取消</el-button>
          <!-- <el-button type="primary" @click="handleRequest">确认</el-button> -->
          <ReButton type="primary" debounce auto-loading @click="handleRequest"
            >确认</ReButton
          >
        </span>
      </template>
    </el-dialog>

    <el-dialog
      title="驳回"
      v-model="dialogVisible"
      destroy-on-close
      width="600px"
    >
      <reject-view
        v-model:dialogVisible="dialogVisible"
        :taskId="props.taskId"
        :recordId="props.recordId"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import ReFastInput from "/@/components/ReFastInput/index.vue";

import { reactive, ref, defineProps, onMounted, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
// import CheckContent from "../processInfo/CheckContent.vue"
// import ApprovalInfo from "../processInfo/ApprovalInfo.vue"
// import BasicInfo from "../processInfo/BasicInfo.vue"
import { storageLocal } from "/@/utils/storage";
import NotifMessage from "/@/utils/message/notification";
import { postFlowSubmit } from "/@/api/quality";
import RejectView from "../dialog/RejectView.vue";
import { postGetStorageTmpData, postStorageTmpData } from "/@/api/acceptance";

import ReButton from "/@/components/ReButton/index.vue";

const router = useRouter();
const route = useRoute();
const formRef = ref<HTMLFormElement | null>(null) as any;

const props = defineProps({
  checkContentList: {
    type: Array,
    default: () => []
  },
  taskId: {
    type: String,
    default: ""
  },
  projectTeam: {
    type: Array,
    default: () => []
  },
  recordId: {
    type: Number
  }
});

const formData = reactive({
  approveResult: "1",
  opinion: ""
});

let currentTeam = reactive({
  userName: "",
  userId: ""
}); // 下一节点的处理人信息

let outterId = ref("");
let effective = ref("");

let dialogVisible = ref(false);

let commitVisible = ref(false);

const formRules = {
  approveResult: {
    required: true,
    message: "请选择审批结果",
    trigger: "change"
  },
  opinion: {
    required: true,
    message: "请填写审批意见",
    trigger: "change"
  }
};

const handleBack = () => {
  // TODO  根据来源进行处理
  if (route.query.source === "work") {
    router.push({ path: "/work/dashboard", replace: true });
  } else {
    router.push({ path: "/quality/inspection", replace: true });
  }
};

const handleSubmit = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  props.projectTeam.forEach(item => {
    if ((item as any)?.roleCode === "3") {
      currentTeam.userName = (item as any)?.userName;
      currentTeam.userId = (item as any)?.userId;
    }
  });
  commitVisible.value = true;
};

const handleRequest = async done => {
  try {
    const { instanceId, nodeDefId, flowId, contractId } = route.query;
    const info = storageLocal.getItem("info");
    const params = {
      formBaseInfo: {
        id: contractId,
        ...formData
      },
      formSubMap: {
        flowType: 11,
        nodeId: nodeDefId,
        isRectification: "", // 质量整改通过传0
        approveResult: formData.approveResult,
        approvalNode: "102",
        recheckPass: "",
        isChargehand: "",
        flowId,
        procInstId: instanceId,
        taskId: props.taskId,
        opinion: `审批意见：${formData.opinion}`,
        assignee: info?.userId ?? ""
      },
      tmpStorage: {
        nodeId: nodeDefId,
        flowId,
        taskId: props.taskId,
        handlerId: info?.userId ?? "",
        userId: info?.userId ?? "",
        valueJson: JSON.stringify({
          ...formData,
          flowInfoId: flowId
        })
      }
    };

    // 根据后端要求。传一个outterId
    if (outterId.value) {
      const joinData = Object.assign(params.tmpStorage, {
        outterId: outterId.value
      });
      params.tmpStorage = joinData;
    }
    // 根据后端要求。传一个effective
    if (effective.value) {
      const joinData = Object.assign(params.tmpStorage, {
        effective: effective.value
      });
      params.tmpStorage = joinData;
    }
    const { code, data } = await postFlowSubmit(params);
    console.log(code, data);
    if (code === 200) {
      NotifMessage.success("提交成功");
      handleBack();
    }
  } catch (err) {
    console.log(err);
  } finally {
    setTimeout(() => {
      done();
    }, 1000);
  }
};

const handleReject = async () => {
  dialogVisible.value = true;
};

const handleSave = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  const info = storageLocal.getItem("info");
  const { flowId, nodeDefId } = route.query;
  let params = {
    nodeId: nodeDefId,
    taskId: props.taskId,
    flowId,
    handlerId: info ? info?.userId : "",
    valueJson: JSON.stringify(formData)
  };

  if (outterId.value) {
    params = Object.assign(params, { outterId: outterId.value });
  }

  if (effective.value) {
    params = Object.assign(params, { effective: effective.value });
  }

  try {
    const { code, message } = await postStorageTmpData(params);
    if (code === 200) {
      NotifMessage.success("保存成功");
      // router.replace("/acceptance/arrival");
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

const getStorageTmpData = async () => {
  const info = storageLocal.getItem("info");
  const { flowId, nodeDefId } = route.query;
  let params = {
    nodeId: nodeDefId,
    taskId: props.taskId,
    flowId,
    handlerId: info ? info?.userId : ""
  };

  const { code, data } = await postGetStorageTmpData(params);
  if (code === 200) {
    if (data?.valueJson) {
      const { opinion, approveResult } = JSON.parse(data.valueJson);
      formData.opinion = opinion;
      formData.approveResult = String(approveResult);
      outterId.value = data.outterId;
      effective.value = data?.effective ?? "";
    }
  }
};

// 快速输入
const emitFastInput = tag => {
  formData.opinion = `${formData.opinion}${tag}`;
};

onMounted(() => {
  nextTick(() => {
    getStorageTmpData();
  });
});
</script>

<style lang="scss" scoped>
.card-box {
  width: 100%;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  .form__content {
    flex: 1;
    width: inherit;
  }
}
.content-footer {
  margin-top: 20px;
  width: inherit;
  height: 40px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
